package com.threadStudy;

import java.util.concurrent.CountDownLatch;

/**
 * Created by shaxj on 16/6/16.
 */
public class Interrupt {

    public static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch start = new CountDownLatch(3);
        ThreadClass t1 = new ThreadClass(start);
        ThreadClass t2 = new ThreadClass(start);
        ThreadClass t3 = new ThreadClass(start);

        t1.start();
        t2.start();
        t3.start();

//        t1.interrupt();
        start.await();

        // 如果不加lock会抛出异常
//        IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.
//        根据官方注释解释，“当前线程不是对象管理者的所有者”
        synchronized (lock) {
            System.out.println("notify start");
            lock.notifyAll();
            System.out.println("notify end");
        }
    }

    public static class ThreadClass extends Thread {
        CountDownLatch start;

        ThreadClass(CountDownLatch start) {
            this.start = start;
        }

        @Override
        public void run() {
            System.out.println(this.getId() + ",run");
            // 注意：wait的时候，不会占用锁
            synchronized (lock) {
                try {
                    System.out.println("currentThread:" + this.getName());
                    start.countDown();
                    System.out.println("start.getCount = " + start.getCount());
                    lock.wait();
                    System.out.println("currentThread:" + this.getName() + "alter wait");
//                    sleep(5000);
//                    System.out.println("currentThread:" + this.getName() + "alter sleep");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // TODO 获取任务对象,跳出synchronized 模块,否则继续wait
            }
        }
    }
}
